home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16760 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: druid.borland.com!usenet
  2. From: pete@borland.com (Pete Becker)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Friend vs. Member function for operator overload
  5. Date: 11 Apr 1996 21:55:48 GMT
  6. Organization: Borland International
  7. Message-ID: <4kjv54$19t@druid.borland.com>
  8. References: <4kj55n$mv2@homenet.hom.net>
  9. NNTP-Posting-Host: pbecker.borland.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=ISO-8859-1
  12. X-Newsreader: WinVN 0.99.5
  13.  
  14. In article <4kj55n$mv2@homenet.hom.net>, dengel@hom.net says...
  15. >
  16. >Can anyone tell me the relative advantages and disadvantages of using
  17. >a friend function vs. a member function to overload an operator, such
  18. >as addition?  For example, suppose you have a Complex class (I'm not
  19. >interested in building a complex class--I'm just using this for an
  20. >example.):
  21. >
  22. >class Complex {
  23. >private:
  24. >        int real, imag;
  25. >. . . 
  26. >};
  27. >
  28. >Now, you would want to be able to add complex numbers, like so:
  29. >
  30. >Complex a, b, c;
  31. >
  32. >a = (some complex number);
  33. >b = (some complex number);
  34. >c = a + b;
  35. >
  36. >Now, as far as I can tell, there are two general approaches to this.
  37. >One is the declare a friend function header in the class definition:
  38. >
  39. >friend Complex operator+( Complex& a, Complex& b) ;
  40. >
  41. >and then define that function something like:
  42. >
  43. >Complex operator+( Complex& const a, Complex& const b) {
  44. >        Complex temp;
  45. >        temp.real = a.real + b.real;
  46. >        temp.imag = a.imag + b.imag;
  47. >        return temp;
  48. >}
  49. >
  50. >The other way is to put the operator in the class definition itself:
  51. >
  52. >Complex operator+( Complex& const a) {
  53. >        Complex temp;
  54. >        temp.real = this->real + a.real;
  55. >        temp.imag = this->imag + a.imag;
  56. >        return temp;
  57. >}
  58. >
  59. >Can anyone tell me if one of these the "preferred" way of doing it?
  60. >And, what are the advantages and disadvantages of each?
  61.  
  62. The preferred way is to make the usual binary operators globals. That way you 
  63. can write expressions like this:
  64.  
  65. complex c = 1;
  66. complex d = 1 + c;
  67.  
  68.     If the + operator were a member there would be no way for the compiler 
  69. to evaluate 1 + c, because 1 is not of type complex. When the function is 
  70. global the compiler can convert it to a complex and use the global operator.
  71.     Further, the global function usually doesn't need to be a friend. Just 
  72. implement it with +=, which should be a member.
  73.     -- Pete
  74.  
  75.